import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'

// API基础配置
export const API_CONFIG = {
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
}

// 响应数据接口
export interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
  timestamp: string
}

// 分页响应接口
export interface PageResponse<T = any> {
  content: T[]
  totalElements: number
  totalPages: number
  size: number
  number: number
  first: boolean
  last: boolean
  empty: boolean
}

// 错误响应接口
export interface ApiError {
  code: number
  message: string
  details?: string
  timestamp: string
}

// 创建axios实例
const createAxiosInstance = (): AxiosInstance => {
  const instance = axios.create(API_CONFIG)

  // 请求拦截器
  instance.interceptors.request.use(
    (config: any) => {
      // 添加认证token（如果存在）
      const token = localStorage.getItem('auth_token')
      if (token && config.headers) {
        config.headers.Authorization = `Bearer ${token}`
      }

      // 添加请求时间戳
      if (config.params) {
        config.params._t = Date.now()
      } else {
        config.params = { _t: Date.now() }
      }

      console.log(`[API Request] ${config.method?.toUpperCase()} ${config.url}`, {
        params: config.params,
        data: config.data,
      })

      return config
    },
    (error: AxiosError) => {
      console.error('[API Request Error]', error)
      return Promise.reject(error)
    }
  )

  // 响应拦截器
  instance.interceptors.response.use(
    (response: AxiosResponse<ApiResponse>) => {
      console.log(`[API Response] ${response.config.method?.toUpperCase()} ${response.config.url}`, {
        status: response.status,
        data: response.data,
      })

      // 检查业务状态码
      if (response.data.code !== 200) {
        const error = new Error(response.data.message) as any
        error.code = response.data.code
        error.response = response
        throw error
      }

      return response
    },
    (error: AxiosError<ApiError>) => {
      console.error('[API Response Error]', error)

      // 处理网络错误
      if (!error.response) {
        throw new Error('网络连接失败，请检查网络设置')
      }

      // 处理HTTP状态码错误
      const { status, data } = error.response
      let message = '请求失败'

      switch (status) {
        case 400:
          message = data?.message || '请求参数错误'
          break
        case 401:
          message = '未授权，请重新登录'
          // 清除本地token
          localStorage.removeItem('auth_token')
          // 可以在这里跳转到登录页面
          break
        case 403:
          message = '权限不足，无法访问'
          break
        case 404:
          message = '请求的资源不存在'
          break
        case 500:
          message = data?.message || '服务器内部错误'
          break
        case 502:
          message = '网关错误'
          break
        case 503:
          message = '服务暂时不可用'
          break
        default:
          message = data?.message || `请求失败 (${status})`
      }

      const apiError = new Error(message) as any
      apiError.code = status
      apiError.response = error.response
      apiError.originalError = error

      throw apiError
    }
  )

  return instance
}

// 导出axios实例
export const apiClient = createAxiosInstance()

// 导出请求方法
export const api = {
  get: <T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<ApiResponse<T>>> =>
    apiClient.get(url, config),
  
  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<ApiResponse<T>>> =>
    apiClient.post(url, data, config),
  
  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<ApiResponse<T>>> =>
    apiClient.put(url, data, config),
  
  delete: <T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<ApiResponse<T>>> =>
    apiClient.delete(url, config),
  
  patch: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<ApiResponse<T>>> =>
    apiClient.patch(url, data, config),
}

export default api
